// ------------------------------------------------------------------------------
//  <once-generated>
//     这个文件只生成一次，再次生成不会被覆盖。
//  </once-generated>
//
//  <copyright file="organization.module.ts" company="astrom">
//      
//  </copyright>
//  <site></site>
//  <last-editor>Bruce.Yu</last-editor>
// -----------------------------------------------------------------------

import { Component, OnInit, Injector, ViewChild } from '@angular/core';
import { SFUISchema, SFSchema } from '@delon/form';
import { OsharpSTColumn } from '@shared/osharp/services/alain.types';
import { STComponentBase } from '@shared/osharp/components/st-component-base';
import { NzTreeNodeOptions, NzTreeComponent } from 'ng-zorro-antd';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { AjaxResult } from '@shared/osharp/osharp.model';
import { UsersComponent } from '@shared/components/users/users.component';


@Component({
  selector: 'app-organization',
  templateUrl: './organization.component.html',
  styles: []
})
export class OrganizationComponent extends STComponentBase implements OnInit {
@ViewChild('tree',{static:true}) orgTree:NzTreeComponent;
@ViewChild('orgUsers',{static:true}) orgUsers:UsersComponent;
treeData: NzTreeNodeOptions[] = [];
orgForm:FormGroup;



  constructor(injector: Injector,private fb:FormBuilder) {
    super(injector);
    this.moduleName = 'organization';
  }

  get Id(){return this.orgForm.get('Id')}
  get Name(){return this.orgForm.get('Name')}
  get Path(){return this.orgForm.get('Path')}
  get ParentId(){return this.orgForm.get('ParentId')}

  ngOnInit() {
    super.InitBase();
    this.loadTreeData();
    this.createForm();
  }
  createForm() {
    this.orgForm = this.fb.group(
      {
          Id:['',[Validators.required,Validators.maxLength(10)]],
          Name:['',[Validators.required,Validators.maxLength(20),Validators.minLength(1)]],
          Path:[''],
          ParentId:[''],
      }
    );
  }

  loadTreeData() {
    
    let url = "api/Admin/Organization/GetNZTreeData";
    if (!url) {
      return;
    }
    this.http.get(url)
    .subscribe(res => {
      this.treeData = res;
    });
  }

  onIdChange(e)
  {
    if(this.ParentId.value===""){
      this.Path.setValue(`${(e.target).value}`);
    }
    else{
      this.Path.setValue(`${this.ParentId.value}/${(e.target).value}`);
    }
  }

  createSibling()
  {
    this.orgForm.reset();
    let pId='';
    if(this.orgTree.getSelectedNodeList().length>0)
    {
      if (this.orgTree.getSelectedNodeList()[0].parentNode !== null)
      {
        pId=this.orgTree.getSelectedNodeList()[0].parentNode.key;
      }
      
    }
    this.ParentId.setValue(pId);
    this.editModal.open();
  }

  createSon()
  {
    this.orgForm.reset();
    let pId=null;
    if(this.orgTree.getSelectedNodeList().length>0)
    {
      pId=this.orgTree.getSelectedNodeList()[0].key;
    }
    this.ParentId.setValue(pId);
    this.editModal.open();
  }

  cancel()
  {
    this.editModal.close();
  }

  submit()
  {
    if (this.ParentId.value==="") 
    {
      this.ParentId.setValue(null);
    }
    if(this.orgForm.valid)
    {
      let url = this.createUrl;
      this.http.post<AjaxResult>(url, [this.orgForm.value]).subscribe(result => {
        this.osharp.ajaxResult(result, () => {
          this.editModal.close();
          this.loadTreeData();
        });
      });
    }
  }

  delNode(){
    if(this.orgTree.getSelectedNodeList().length>0)
    {
      let id=this.orgTree.getSelectedNodeList()[0].key;
      let url = this.deleteUrl;
      
      this.http.post<AjaxResult>(url, [id]).subscribe(result => {
        this.osharp.ajaxResult(result, () => {
          this.loadTreeData();
        });
      });
    }
  }

  
  treeNodeClicked()
  {
    const orgUserUrl = 'api/admin/organization/users';
    if(this.orgTree.getSelectedNodeList().length>0)
    {
      let id = this.orgTree.getSelectedNodeList()[0].key;
      this.orgUsers.setUrl(orgUserUrl,{org:id});
    }
  }

  protected GetSTColumns(): OsharpSTColumn[] {
    let columns: OsharpSTColumn[] = [
      {
        title: '操作', fixed: 'left', width: 65, buttons: [{
          text: '操作', children: [
            { text: '编辑', icon: 'edit', acl: 'Root.Admin.LMS.Organization.Update', click: row => this.edit(row) },
            { text: '删除', icon: 'delete', type: 'del', acl: 'Root.Admin.LMS.Organization.Delete', click: row => this.delete(row) },
          ]
        }]
      },
      { title: '编号', index: 'Id', sort: true,  editable: true, filterable: true, ftype: 'string' },
      { title: '名称', index: 'Name', sort: true, editable: true, filterable: true, ftype: 'string' },
      { title: '路径', index: 'Path', sort: true, editable: true, filterable: true, ftype: 'string' },
      { title: '描述', index: 'Remark', sort: true, editable: true, filterable: true, ftype: 'string' },
      { title: '父节点', index: 'Parent', ftype: 'string' },
      { title: '父编号', index: 'ParentId', sort: true, editable: true, filterable: true, ftype: 'string' },
      { title: '创建时间', index: 'CreatedTime', sort: true, filterable: true, type: 'date' },
    ];
    return columns;
  }

  protected GetSFSchema(): SFSchema {
    let schema: SFSchema = {
      properties: this.ColumnsToSchemas(this.columns),
      required: ['Id','Name', 'Path']
    };
    return schema;
  }

  protected GetSFUISchema(): SFUISchema {
    let ui: SFUISchema = {
      '*': { spanLabelFixed: 100, grid: { span: 24 } },
      $Name: { grid: { span: 24 } },
      $Path: { grid: { span: 24 } },
      $Remark: { grid: { span: 24 } },
      $ParentId: { grid: { span: 24 } }
    };
    return ui;
  }
}

